import { getUserInfo, removeToken, removeUserInfo } from '../../utils/storage'
import config from '../../config/index'
import { models, RentModel } from '../../enums/model'
import { getAreaAll } from '../../api/contracts'
import { addHouseRes } from '../../api/houseRes'
import { addHouseMedia } from '../../api/houseMedia'

// let qqmapwx = require('../../lib/qqmap-wx-jssdk.js')
// let chooseLocation = requirePlugin('chooseLocation')

interface MediaType {
  id: number
  url: string
  type: string
  poster?: string
  isPoster: boolean
}

Page({
  qqmapsdk: null as any,
  mapCTX: null as any,
  data: {
    house_name: '', //名称
    house_rent: 0, //租金
    house_use: '小区', //类型
    house_floor: '', //楼层
    house_type: '1-1-1', //户型
    house_area: '', //面积
    house_mode: RentModel.FULL, //租房方式
    house_peace: '花桥', //区域
    house_address: '',
    spec_address: '',
    pay_method: '',
    house_plot: '',
    peace_list: [],
    house_position: '', //位置
    landload_id: '', //房东id
    landload_phone: '', //房东电话
    house_remark: '',
    house_tag: '',
    userInfo: {
      id: '',
      nick_name: '',
      phone: ''
    } as User,
    config,
    use_list: ['公寓', '小区', '别墅', '自建房'],
    mode_list: models.map((item: any) => {
      return {
        label: item.label,
        value: item.value
      }
    }),
    mode_label: models[0].label,
    position_label: '',
    showUse: false,
    showMode: false,
    showPeace: false,
    showPosition: false,
    longitude: null as null | number,
    latitude: null as null | number,
    media_list: [] as MediaType[],
    marks: [] as any[],
    room: '' as string | number,
    living: '' as string | number,
    toilet: '' as string | number,
    cash: '' as string | number,
    pay: '' as string | number,
    building: '' as string | number,
    No: '' as string | number
  },
  handleTypeChange() {
    this.setData({
      house_type: `${this.data.room}-${this.data.living}-${this.data.toilet}`
    })
  },
  handleMethodChange() {
    this.setData({
      pay_method: `${this.data.cash}-${this.data.pay}`
    })
  },
  handleSpecChange() {
    this.setData({
      spec_address: `${this.data.building}-${this.data.No}`
    })
  },
  choooseAddress() {
    // const referer = '房源位置'
    // let location = JSON.stringify({
    //   latitude: this.data.latitude,
    //   longitude: this.data.longitude
    // })
    // wx.navigateTo({
    //   // url: `plugin://chooseLocation/index?key=${config.mapKey}&referer=${referer}&location=${location}`
    //   url: `plugin://chooseLocation/index?key=${config.mapKey}&referer=${referer}`
    // })

    //弹出地图
    // this.handleShowPosition()
    let that = this
    wx.chooseLocation({
      success: function (res: any) {
        if (res.errMsg === 'chooseLocation:ok') {
          that.setData({
            longitude: res.longitude,
            latitude: res.latitude,
            house_address: res.address,
            house_position: `${res.longitude},${res.latitude}`
          })
        }
      }
    })
  },
  handleShowMode() {
    this.setData({
      showMode: !this.data.showMode
    })
  },
  handleShowUse() {
    this.setData({
      showUse: !this.data.showUse
    })
  },
  handleShowPeace() {
    this.setData({
      showPeace: !this.data.showPeace
    })
  },
  handleShowPosition() {
    this.setData({
      showPosition: !this.data.showPosition
    })
  },
  onModeChange(event: any) {
    const { value } = event.detail
    this.setData({
      house_mode: value.value,
      mode_label: value.label
    })
    this.handleShowMode()
  },
  onPeaceChange(event: any) {
    const { value } = event.detail
    this.setData({
      house_peace: value
    })
    this.handleShowPeace()
  },
  onUseChange(event: any) {
    const { value } = event.detail
    this.setData({
      house_use: value
    })
    this.handleShowUse()
  },
  async getPeaceData() {
    const res = await getAreaAll()
    if (res.statusCode === config.SUCCESS_CODE) {
      this.setData({
        peace_list: res.data.map((item: any) => {
          return item.item_value
        })
      })
    }
  },
  getData() {
    const user = getUserInfo()
    if (user) {
      this.setData({
        userInfo: JSON.parse(user),
        landload_id: JSON.parse(user).id,
        landload_phone: JSON.parse(user).phone
      })
    }
  },
  //初始化坐标
  initLocation() {
    wx.getFuzzyLocation({
      type: "gcj02",
      success: (res: any) => {
        let marks = [
          {
            id: 0,
            iconPath: '../../static/icons/icon-position.png',
            longitude: res.longitude,
            latitude: res.latitude,
            width: 34,
            height: 40
          },
          {
            id: 1,
            iconPath: '../../static/icons/icon-building.png',
            longitude: res.longitude,
            latitude: res.latitude,
            width: 30,
            height: 35
          }
        ]
        this.setData({
          longitude: res.longitude,
          latitude: res.latitude,
          house_position: `${res.longitude},${res.latitude}`,
          marks
        })
      }
    })
  },
  chooseUpload() {
    wx.chooseMedia({
      count: 9,
      mediaType: ['mix'],
      success: (res: any) => {
        if (res.errMsg === 'chooseMedia:ok') {
          let media_list = res.tempFiles.map((item: any, index: number) => {
            return {
              id: index,
              url: item.tempFilePath,
              type: item.fileType,
              poster: item.thumbTempFilePath,
              isPoster: false
            }
          }) as MediaType[]
          if (media_list.filter(item => item.type === 'image').length > 8) {
            wx.showToast({
              title: '图片数量超过8张，请重新上传',
              icon: 'none'
            })
            return
          }
          if (media_list.filter(item => item.type === 'video').length > 1) {
            wx.showToast({
              title: '视频数量超过1个，请重新上传',
              icon: 'none'
            })
            return
          }
          this.setData({
            media_list
          })
        }
      }
    })
  },
  prviewMedia(e: WechatMiniprogram.TouchEvent) {
    let id = e.currentTarget.dataset.id
    wx.previewMedia({
      current: id,
      sources: this.data.media_list as WechatMiniprogram.MediaSource[]
    })
  },
  delMedia(e: any) {
    let id = e.currentTarget.dataset.id
    let new_list = this.data.media_list.filter(item => item.id !== id)
    this.setData({
      media_list: new_list
    })
  },
  posterMedia(e: any) {
    let index = e.currentTarget.dataset.index
    let media_list = this.data.media_list.map((item: MediaType) => {
      return {
        ...item,
        isPoster: false
      }
    }) as MediaType[]
    media_list[index].isPoster = true
    this.setData({
      media_list
    })
  },
  async sub() {
    // if (this.data.media_list.filter((item: MediaType) => item.type === 'image').length === 0) {
    //   wx.showToast({
    //     title: '请上传房源图片!',
    //     icon: 'none'
    //   })
    //   return
    // }
    wx.showLoading({
      title: '上传房源中'
    })
    let that = this
    let resData: HouseRes = {
      house_rent: +this.data.house_rent,
      house_use: this.data.house_use,
      house_floor: this.data.house_floor,
      house_type: this.data.house_type,
      house_area: this.data.house_area,
      house_mode: this.data.house_mode,
      house_peace: this.data.house_peace,
      house_position: this.data.house_position,
      house_address: this.data.house_address,
      landload_id: this.data.userInfo.id,
      landload_phone: this.data.userInfo.phone,
      pay_method: this.data.pay_method,
      house_plot: this.data.house_plot,
      spec_address: this.data.spec_address,
      house_remark: this.data.house_remark,
      house_tag: this.data.house_tag
    }
    const housedataRes = await addHouseRes(resData)
    if (this.data.building === '' || this.data.No === '' || this.data.living === '' || this.data.room === '' || this.data.toilet === '' || this.data.cash === '' || this.data.pay === '') {
      wx.showToast({
        title: '请补全必要信息',
        icon: 'none'
      })
      return
    }
    if (housedataRes.statusCode === config.ARG_CODE) {
      wx.showToast({
        title: housedataRes.message,
        icon: 'none'
      })
      return
    }
    if (housedataRes.statusCode === config.UNI_CODE) {
      wx.showToast({
        title: '登录状态已失效，请重新登录',
        icon: 'none'
      })
      removeToken()
      removeUserInfo()
      const lTimer = setTimeout(() => {
        wx.switchTab({
          url: '/pages/me/me'
        })
        clearTimeout(lTimer)
      }, 1000)
      return
    }
    if (housedataRes.statusCode === config.CREATED_CODE) {
      wx.showLoading({
        title: '上传文件中'
      })
      this.data.media_list.forEach((item: MediaType) => {
        wx.uploadFile({
          url: config.BaseUrl + '/api/upload/image',
          filePath: item.url,
          name: 'file',
          success: async (res) => {
            const mediaRes = JSON.parse(res.data)
            if (mediaRes.statusCode !== config.CREATED_CODE) {
              wx.hideLoading()
              wx.showToast({ title: '上传文件失败', icon: 'none' })
              return
            }
            const file = mediaRes.data
            let data: HouseMedia = {
              media_url: file.path.replace(/\\/g, '/'),
              media_type: file.mimetype === 'image/jpeg' || file.mimetype === 'image/png' ? 'image' : 'video',
              houseResId: housedataRes.data,
              sub_user: that.data.userInfo.id,
              isPoster: item.isPoster
            }
            const addMediaRes = await addHouseMedia(data)
            if (addMediaRes.statusCode !== config.CREATED_CODE) {
              wx.hideLoading()
              wx.showToast({ title: '上传失败，请重试', icon: 'none' })
              return
            }
          }
        })
      })
      wx.hideLoading()
      wx.showToast({
        title: '上传完成',
        icon: 'success'
      })
      const timer = setTimeout(() => {
        wx.navigateBack()
        clearTimeout(timer)
      }, 1000)
    } else {
      wx.hideLoading()
      wx.showToast({
        title: '上传失败，请重试',
        icon: 'none'
      })
    }
  },
  onLoad() {
    this.getData()
    this.getPeaceData()
    this.mapCTX = wx.createMapContext('map')
  },
  regionchange(res: any) {
    if (res.type == 'end') {
      let centerLoc = res.detail.centerLocation
      let marks = [
        {
          id: 0,
          iconPath: '../../static/icons/icon-position.png',
          longitude: this.data.longitude,
          latitude: this.data.latitude,
          width: 34,
          height: 40
        },
        {
          id: 1,
          iconPath: '../../static/icons/icon-building.png',
          longitude: centerLoc.longitude,
          latitude: centerLoc.latitude,
          width: 30,
          height: 35
        }
      ]
      this.setData({
        marks,
        house_position: `${centerLoc.longitude},${centerLoc.latitude}`
      })
    }
  },
  onReady() {
    this.initLocation()
  },
  onShow() {
    // const location = chooseLocation.getLocation();
    // if(location) {
    //   this.setData({
    //     longitude: location.longitude,
    //     latitude: location.latitude,
    //     house_position: `${location.longitude},${location.latitude}`,
    //     position_label: location.address
    //   })
    // }
  }
})

